<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<el-icon size="24"><Medal /></el-icon>
				运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="user-info">
				<el-dropdown trigger="click">
					<div class="user-avatar">
						<el-avatar :size="40" :src="avatarUrl" icon="UserFilled"></el-avatar>
						<span class="username">{{ currentUser?.realName || '管理员' }}</span>
						<el-icon><ArrowDown /></el-icon>
					</div>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item @click="handleLogout">
								<el-icon><SwitchButton /></el-icon>
								退出登录
							</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }" @click="navigateTo('/admin')">
				<el-icon><Monitor /></el-icon>
				<span>系统管理</span>
			</div>
			<div class="menu-item active">
				<el-icon><User /></el-icon>
				<span>用户管理</span>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/projects' }" @click="navigateTo('/admin/projects')">
				<el-icon><List /></el-icon>
				<span>项目管理</span>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }" @click="navigateTo('/admin/schedule')">
				<el-icon><Calendar /></el-icon>
				<span>赛程管理</span>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/judges' }" @click="navigateTo('/admin/judges')">
				<el-icon><Whistle /></el-icon>
				<span>裁判分配</span>
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<!-- 页面标题和操作按钮 -->
			<div class="page-header">
				<div class="page-title">
					<h1>用户管理</h1>
					<p class="page-desc">管理系统用户信息、角色分配和权限控制</p>
				</div>
				<div class="header-actions">
					<el-button type="success" @click="handleExport" :loading="exportLoading">
						<el-icon><Download /></el-icon> 导出数据
					</el-button>
					<el-button type="primary" @click="handleImport">
						<el-icon><Upload /></el-icon> 批量导入
					</el-button>
					<el-button type="primary" @click="handleAdd">
						<el-icon><Plus /></el-icon> 添加用户
					</el-button>
				</div>
			</div>

			<!-- 搜索和筛选区域 -->
			<el-card class="search-card" shadow="hover">
				<el-form :model="searchForm" inline>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="用户名">
								<el-input
									v-model="searchForm.username"
									placeholder="请输入用户名"
									clearable
									:prefix-icon="User"
									@keyup.enter="handleSearch">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="姓名">
								<el-input
									v-model="searchForm.realName"
									placeholder="请输入姓名"
									clearable
									:prefix-icon="UserFilled"
									@keyup.enter="handleSearch">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="班级">
								<el-input
									v-model="searchForm.className"
									placeholder="请输入班级"
									clearable
									:prefix-icon="School"
									@keyup.enter="handleSearch">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="学院">
								<el-input
									v-model="searchForm.college"
									placeholder="请输入学院"
									clearable
									:prefix-icon="OfficeBuilding"
									@keyup.enter="handleSearch">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="角色">
								<el-select
									v-model="searchForm.roleId"
									placeholder="请选择角色"
									clearable
									style="width: 100%">
									<el-option
										v-for="role in roleOptions"
										:key="role.value"
										:label="role.label"
										:value="role.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="状态">
								<el-select
									v-model="searchForm.isActive"
									placeholder="请选择状态"
									clearable
									style="width: 100%">
									<el-option label="启用" :value="true">
										<el-tag type="success" size="small">启用</el-tag>
									</el-option>
									<el-option label="禁用" :value="false">
										<el-tag type="danger" size="small">禁用</el-tag>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item>
								<el-button type="primary" @click="handleSearch" :loading="loading">
									<el-icon><Search /></el-icon> 搜索
								</el-button>
								<el-button @click="handleReset">
									<el-icon><Refresh /></el-icon> 重置
								</el-button>
								<el-button type="info" @click="toggleAdvancedSearch">
									<el-icon><Operation /></el-icon> {{ showAdvancedSearch ? '收起' : '高级' }}
								</el-button>
							</el-form-item>
						</el-col>
					</el-row>

					<!-- 高级搜索区域 -->
					<el-collapse-transition>
						<div v-show="showAdvancedSearch" class="advanced-search">
							<el-divider content-position="left">高级搜索</el-divider>
							<el-row :gutter="20">
								<el-col :xs="24" :sm="12" :md="8" :lg="6">
									<el-form-item label="手机号">
										<el-input
											v-model="searchForm.phone"
											placeholder="请输入手机号"
											clearable
											:prefix-icon="Phone"
											@keyup.enter="handleSearch">
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="8" :lg="6">
									<el-form-item label="邮箱">
										<el-input
											v-model="searchForm.email"
											placeholder="请输入邮箱"
											clearable
											:prefix-icon="Message"
											@keyup.enter="handleSearch">
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="8" :lg="6">
									<el-form-item label="创建时间">
										<el-date-picker
											v-model="searchForm.dateRange"
											type="daterange"
											range-separator="至"
											start-placeholder="开始日期"
											end-placeholder="结束日期"
											style="width: 100%"
											format="YYYY-MM-DD"
											value-format="YYYY-MM-DD">
										</el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-collapse-transition>
				</el-form>
			</el-card>

			<!-- 用户数据表格 -->
			<el-card class="table-card" shadow="hover">
				<!-- 工具栏 -->
				<div class="table-toolbar">
					<div class="table-info">
						<span class="table-title">用户列表</span>
						<el-tag type="info" size="small">共 {{ pagination.total }} 条记录</el-tag>
					</div>
					<div class="table-actions">
						<el-button-group>
							<el-button
								:size="tableSize"
								@click="tableSize = 'large'"
								:class="{ 'is-active': tableSize === 'large' }">
								大
							</el-button>
							<el-button
								:size="tableSize"
								@click="tableSize = 'default'"
								:class="{ 'is-active': tableSize === 'default' }">
								中
							</el-button>
							<el-button
								:size="tableSize"
								@click="tableSize = 'small'"
								:class="{ 'is-active': tableSize === 'small' }">
								小
							</el-button>
						</el-button-group>
						<el-button
							:icon="RefreshRight"
							@click="loadData"
							:loading="loading"
							circle>
						</el-button>
					</div>
				</div>

				<!-- 表格主体 -->
				<el-table
					:data="tableData"
					v-loading="loading"
					:height="tableHeight"
					stripe
					border
					:size="tableSize"
					@selection-change="handleSelectionChange"
					@sort-change="handleSortChange"
					style="width: 100%">
					<el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
					<el-table-column prop="id" label="ID" width="80" align="center" sortable="custom"></el-table-column>
					<el-table-column prop="username" label="用户名" width="120" align="center" show-overflow-tooltip>
						<template #default="scope">
							<el-link type="primary" @click="handleViewDetail(scope.row)">{{ scope.row.username }}</el-link>
						</template>
					</el-table-column>
					<el-table-column prop="realName" label="真实姓名" width="120" align="center" sortable="custom">
						<template #default="scope">
							<el-avatar :size="32" :src="scope.row.avatar" icon="UserFilled"></el-avatar>
							<span style="margin-left: 8px">{{ scope.row.realName }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="gender" label="性别" width="80" align="center">
						<template #default="scope">
							<el-tag :type="scope.row.gender === '男' ? 'primary' : 'danger'" size="small">
								{{ scope.row.gender || '-' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="className" label="班级" width="150" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="college" label="学院" width="180" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="phone" label="手机号" width="130" align="center">
						<template #default="scope">
							<span v-if="scope.row.phone">{{ maskPhone(scope.row.phone) }}</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column prop="email" label="邮箱" min-width="200" show-overflow-tooltip></el-table-column>
					<el-table-column prop="roleName" label="角色" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getRoleTagType(scope.row.roleName)" size="small">
								{{ scope.row.roleName }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="isActive" label="状态" width="80" align="center">
						<template #default="scope">
							<el-switch
								v-model="scope.row.isActive"
								:loading="scope.row.statusLoading"
								@change="handleToggleStatus(scope.row)"
								active-color="#67C23A"
								inactive-color="#F56C6C">
							</el-switch>
						</template>
					</el-table-column>
					<el-table-column prop="createdAt" label="创建时间" width="160" align="center" sortable="custom">
						<template #default="scope">
							{{ formatDateTime(scope.row.createdAt) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" width="220" align="center" fixed="right">
						<template #default="scope">
							<el-button-group>
								<el-tooltip content="查看详情" placement="top">
									<el-button
										type="primary"
										:icon="View"
										size="small"
										@click="handleViewDetail(scope.row)">
									</el-button>
								</el-tooltip>
								<el-tooltip content="编辑" placement="top">
									<el-button
										type="primary"
										:icon="Edit"
										size="small"
										@click="handleEdit(scope.row)">
									</el-button>
								</el-tooltip>
								<el-tooltip content="重置密码" placement="top">
									<el-button
										type="info"
										:icon="Key"
										size="small"
										@click="handleResetPassword(scope.row)">
									</el-button>
								</el-tooltip>
								<el-tooltip content="删除" placement="top">
									<el-button
										type="danger"
										:icon="Delete"
										size="small"
										@click="handleDelete(scope.row)">
									</el-button>
								</el-tooltip>
							</el-button-group>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页控制 -->
				<div class="pagination-container">
					<el-pagination
						v-model:current-page="pagination.currentPage"
						v-model:page-size="pagination.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						:total="pagination.total"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						background>
					</el-pagination>
				</div>

				<!-- 批量操作栏 -->
				<div class="batch-operations" v-if="selectedUsers.length > 0">
					<div class="batch-info">
						<el-icon><Select /></el-icon>
						<span>已选择 {{ selectedUsers.length }} 项</span>
					</div>
					<div class="batch-actions">
						<el-button-group>
							<el-button type="danger" @click="handleBatchDelete" :loading="batchLoading">
								<el-icon><Delete /></el-icon> 批量删除
							</el-button>
							<el-button type="warning" @click="handleBatchDisable" :loading="batchLoading">
								<el-icon><Lock /></el-icon> 批量禁用
							</el-button>
							<el-button type="success" @click="handleBatchEnable" :loading="batchLoading">
								<el-icon><Unlock /></el-icon> 批量启用
							</el-button>
							<el-button type="info" @click="handleBatchAssignRole" :loading="batchLoading">
								<el-icon><UserFilled /></el-icon> 分配角色
							</el-button>
						</el-button-group>
					</div>
				</div>
			</el-card>

			<!-- 用户表单对话框 -->
			<el-dialog
				:title="dialogTitle"
				v-model="dialogVisible"
				width="600px"
				:before-close="handleDialogClose"
				:close-on-click-modal="false"
				destroy-on-close>
				<el-form
					:model="userForm"
					:rules="userFormRules"
					ref="userFormRef"
					label-width="100px"
					:size="formSize">
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="用户名" prop="username">
								<el-input
									v-model="userForm.username"
									:disabled="isEdit"
									placeholder="请输入用户名"
									:prefix-icon="User">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="真实姓名" prop="realName">
								<el-input
									v-model="userForm.realName"
									placeholder="请输入真实姓名"
									:prefix-icon="UserFilled">
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="性别" prop="gender">
								<el-radio-group v-model="userForm.gender">
									<el-radio label="男">男</el-radio>
									<el-radio label="女">女</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="角色" prop="roleId">
								<el-select
									v-model="userForm.roleId"
									placeholder="请选择角色"
									style="width: 100%">
									<el-option
										v-for="role in roleOptions"
										:key="role.value"
										:label="role.label"
										:value="role.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="班级" prop="className">
								<el-input
									v-model="userForm.className"
									placeholder="请输入班级"
									:prefix-icon="School">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="学院" prop="college">
								<el-input
									v-model="userForm.college"
									placeholder="请输入学院"
									:prefix-icon="OfficeBuilding">
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :xs="24" :sm="12">
							<el-form-item label="手机号" prop="phone">
								<el-input
									v-model="userForm.phone"
									placeholder="请输入手机号"
									:prefix-icon="Phone">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="邮箱" prop="email">
								<el-input
									v-model="userForm.email"
									placeholder="请输入邮箱"
									:prefix-icon="Message">
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20" v-if="!isEdit">
						<el-col :xs="24" :sm="12">
							<el-form-item label="密码" prop="passwordHash">
								<el-input
									v-model="userForm.passwordHash"
									type="password"
									placeholder="请输入密码"
									show-password
									:prefix-icon="Lock">
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12">
							<el-form-item label="确认密码" prop="confirmPassword">
								<el-input
									v-model="userForm.confirmPassword"
									type="password"
									placeholder="请确认密码"
									show-password
									:prefix-icon="Lock">
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="状态" prop="isActive">
								<el-switch
									v-model="userForm.isActive"
									active-text="启用"
									inactive-text="禁用"
									active-color="#67C23A"
									inactive-color="#F56C6C">
								</el-switch>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleDialogClose">取消</el-button>
						<el-button type="primary" @click="handleSave" :loading="saveLoading">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 用户详情对话框 -->
			<el-dialog
				title="用户详情"
				v-model="detailDialogVisible"
				width="500px">
				<div v-if="currentUserDetail" class="user-detail">
					<el-descriptions :column="2" border>
						<el-descriptions-item label="头像">
							<el-avatar :size="60" :src="currentUserDetail.avatar" icon="UserFilled"></el-avatar>
						</el-descriptions-item>
						<el-descriptions-item label="用户名">{{ currentUserDetail.username }}</el-descriptions-item>
						<el-descriptions-item label="真实姓名">{{ currentUserDetail.realName }}</el-descriptions-item>
						<el-descriptions-item label="性别">{{ currentUserDetail.gender || '-' }}</el-descriptions-item>
						<el-descriptions-item label="角色">
							<el-tag :type="getRoleTagType(currentUserDetail.roleName)">
								{{ currentUserDetail.roleName }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="班级">{{ currentUserDetail.className || '-' }}</el-descriptions-item>
						<el-descriptions-item label="学院">{{ currentUserDetail.college || '-' }}</el-descriptions-item>
						<el-descriptions-item label="手机号">{{ currentUserDetail.phone || '-' }}</el-descriptions-item>
						<el-descriptions-item label="邮箱" :span="2">{{ currentUserDetail.email || '-' }}</el-descriptions-item>
						<el-descriptions-item label="状态">
							<el-tag :type="currentUserDetail.isActive ? 'success' : 'danger'">
								{{ currentUserDetail.isActive ? '启用' : '禁用' }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="创建时间">{{ formatDateTime(currentUserDetail.createdAt) }}</el-descriptions-item>
					</el-descriptions>
				</div>
			</el-dialog>

			<!-- 批量导入对话框 -->
			<el-dialog
				title="批量导入用户"
				v-model="importDialogVisible"
				width="500px">
				<div class="import-content">
					<el-alert
						title="导入说明"
						type="info"
						description="请按照模板格式准备Excel文件，支持批量导入用户信息"
						:closable="false"
						show-icon>
					</el-alert>
					<div class="import-template">
						<el-link type="primary" @click="downloadTemplate">
							<el-icon><Download /></el-icon> 下载导入模板
						</el-link>
					</div>
					<el-upload
						class="upload-demo"
						drag
						ref="upload"
						action=""
						:auto-upload="false"
						:limit="1"
						accept=".xlsx,.xls"
						:on-change="handleFileChange"
						:before-upload="beforeUpload">
						<el-icon class="el-icon--upload"><upload-filled /></el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或<em>点击上传</em>
						</div>
						<template #tip>
							<div class="el-upload__tip">
								只能上传xlsx/xls文件，且不超过5MB
							</div>
						</template>
					</el-upload>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="importDialogVisible = false">取消</el-button>
						<el-button type="primary" @click="handleUpload" :loading="uploadLoading">
							确定上传
						</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 批量分配角色对话框 -->
			<el-dialog
				title="批量分配角色"
				v-model="batchRoleDialogVisible"
				width="400px">
				<el-form :model="batchRoleForm" label-width="80px">
					<el-form-item label="角色">
						<el-select v-model="batchRoleForm.roleId" placeholder="请选择角色" style="width: 100%">
							<el-option
								v-for="role in roleOptions"
								:key="role.value"
								:label="role.label"
								:value="role.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="batchRoleDialogVisible = false">取消</el-button>
						<el-button type="primary" @click="handleConfirmBatchRole" :loading="batchRoleLoading">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>
		</main>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  // 图标组件
  Medal, User, Monitor, List, Calendar, Whistle, ArrowDown, SwitchButton,
  Download, Upload, Plus, Search, Refresh, Operation, UserFilled, View,
  Edit, Delete, Key, Select, Lock, Unlock, School, OfficeBuilding, Phone,
  Message, RefreshRight, UploadFilled
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 导入API接口
import {
  getUserPage, addUser, updateUser, deleteUser, batchDeleteUsers,
  updateUserStatus, resetUserPassword, importUsers, getUserById
} from '@/api/user'

// 路由和状态管理
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const uploadLoading = ref(false)
const exportLoading = ref(false)
const batchLoading = ref(false)
const batchRoleLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const importDialogVisible = ref(false)
const batchRoleDialogVisible = ref(false)
const showAdvancedSearch = ref(false)
const isEdit = ref(false)
const tableSize = ref('default')
const formSize = ref('default')

// 表格高度
const tableHeight = ref(600)

// 搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  className: '',
  college: '',
  roleId: null,
  isActive: null,
  phone: '',
  email: '',
  dateRange: null,
  sortBy: '',
  sortOrder: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const selectedUsers = ref([])

// 用户详情
const currentUserDetail = ref(null)

// 当前用户信息
const currentUser = computed(() => authStore.userInfo || JSON.parse(localStorage.getItem('userInfo')))

// 默认头像URL
const avatarUrl = computed(() => '/img/jstu1.webp')

// 角色选项
const roleOptions = ref([
  { label: '管理员', value: 1 },
  { label: '老师', value: 2 },
  { label: '裁判', value: 3 },
  { label: '学生', value: 4 },
  { label: '志愿者', value: 5 }
])

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  realName: '',
  gender: '',
  className: '',
  college: '',
  phone: '',
  email: '',
  roleId: null,
  passwordHash: '',
  confirmPassword: '',
  isActive: true
})

// 批量角色分配表单
const batchRoleForm = reactive({
  roleId: null
})

// 上传文件
const uploadFile = ref(null)

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '添加用户')

// 表单引用
const userFormRef = ref(null)

// 自定义验证规则 - 确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== userForm.passwordHash) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const userFormRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  passwordHash: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

// 设置表格高度
const setTableHeight = () => {
  // 桌面端表格高度设置
  tableHeight.value = window.innerHeight - 350
}

// 切换高级搜索
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const params = { ...searchForm }
    if (params.dateRange && params.dateRange.length === 2) {
      params.startDate = params.dateRange[0]
      params.endDate = params.dateRange[1]
    }
    delete params.dateRange

    const response = await getUserPage(pagination.currentPage, pagination.pageSize, params)

    if (response.code === 200) {
      tableData.value = response.data.records.map(item => ({
        ...item,
        statusLoading: false
      }))
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    // 用户数据获取失败处理
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    realName: '',
    className: '',
    college: '',
    roleId: null,
    isActive: null,
    phone: '',
    email: '',
    dateRange: null,
    sortBy: '',
    sortOrder: ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadData()
}

// 表格排序改变
const handleSortChange = ({ prop, order }) => {
  searchForm.sortBy = prop
  searchForm.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
  loadData()
}

// 表格选择改变
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 添加用户
const handleAdd = () => {
  isEdit.value = false
  resetUserForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  isEdit.value = true
  try {
    const response = await getUserById(row.id)
    if (response.code === 200) {
      Object.assign(userForm, {
        ...response.data,
        passwordHash: '',
        confirmPassword: ''
      })
      dialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    // 用户信息获取失败处理
    ElMessage.error('获取用户信息失败')
  }
}

// 查看用户详情
const handleViewDetail = async (row) => {
  try {
    const response = await getUserById(row.id)
    if (response.code === 200) {
      currentUserDetail.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取用户详情失败')
    }
  } catch (error) {
    // 用户详情获取失败处理
    ElMessage.error('获取用户详情失败')
  }
}

// 保存用户
const handleSave = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        let response
        if (isEdit.value) {
          // 编辑时不传递密码字段（除非修改了密码）
          const updateData = { ...userForm }
          if (!updateData.passwordHash) {
            delete updateData.passwordHash
          }
          delete updateData.confirmPassword
          response = await updateUser(updateData)
        } else {
          response = await addUser(userForm)
        }

        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        // 用户保存失败处理
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteUser(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      // 用户删除失败处理
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    batchLoading.value = true
    try {
      const userIds = selectedUsers.value.map(user => user.id)
      const response = await batchDeleteUsers(userIds)
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        loadData()
        selectedUsers.value = []
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
      // 批量删除失败处理
      ElMessage.error('批量删除失败')
    } finally {
      batchLoading.value = false
    }
  })
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  // 添加加载状态
  row.statusLoading = true
  const newStatus = !row.isActive
  const action = newStatus ? '启用' : '禁用'

  try {
    const response = await updateUserStatus(row.id, newStatus)
    if (response.code === 200) {
      row.isActive = newStatus
      ElMessage.success(`${action}成功`)
    } else {
      // 恢复原始状态
      row.isActive = !newStatus
      ElMessage.error(response.message || `${action}失败`)
    }
  } catch (error) {
    // 恢复原始状态
    row.isActive = !newStatus
    // 用户状态操作失败处理
    ElMessage.error(`${action}失败`)
  } finally {
    row.statusLoading = false
  }
}

// 批量启用
const handleBatchEnable = () => {
  ElMessageBox.confirm(`确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    batchLoading.value = true
    try {
      const userIds = selectedUsers.value.map(user => user.id)
      // 这里需要后端支持批量状态更新，暂时循环调用
      const promises = userIds.map(id => updateUserStatus(id, true))
      await Promise.all(promises)
      ElMessage.success('批量启用成功')
      loadData()
      selectedUsers.value = []
    } catch (error) {
      // 批量启用失败处理
      ElMessage.error('批量启用失败')
    } finally {
      batchLoading.value = false
    }
  })
}

// 批量禁用
const handleBatchDisable = () => {
  ElMessageBox.confirm(`确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    batchLoading.value = true
    try {
      const userIds = selectedUsers.value.map(user => user.id)
      // 这里需要后端支持批量状态更新，暂时循环调用
      const promises = userIds.map(id => updateUserStatus(id, false))
      await Promise.all(promises)
      ElMessage.success('批量禁用成功')
      loadData()
      selectedUsers.value = []
    } catch (error) {
      // 批量禁用失败处理
      ElMessage.error('批量禁用失败')
    } finally {
      batchLoading.value = false
    }
  })
}

// 批量分配角色
const handleBatchAssignRole = () => {
  batchRoleForm.roleId = null
  batchRoleDialogVisible.value = true
}

// 确认批量分配角色
const handleConfirmBatchRole = async () => {
  if (!batchRoleForm.roleId) {
    ElMessage.warning('请选择角色')
    return
  }

  batchRoleLoading.value = true
  try {
    const userIds = selectedUsers.value.map(user => user.id)
    // 这里需要后端支持批量角色更新，暂时循环调用
    const promises = userIds.map(id => {
      const userData = { id, roleId: batchRoleForm.roleId }
      return updateUser(userData)
    })
    await Promise.all(promises)
    ElMessage.success('批量分配角色成功')
    batchRoleDialogVisible.value = false
    loadData()
    selectedUsers.value = []
  } catch (error) {
    // 批量分配角色失败处理
    ElMessage.error('批量分配角色失败')
  } finally {
    batchRoleLoading.value = false
  }
}

// 重置密码
const handleResetPassword = (row) => {
  ElMessageBox.prompt('请输入新密码', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputValidator: (value) => {
      if (!value || value.length < 6) {
        return '密码长度不能少于6个字符'
      }
      return true
    }
  }).then(async ({ value }) => {
    try {
      const response = await resetUserPassword(row.id, value)
      if (response.code === 200) {
        ElMessage.success('密码重置成功')
      } else {
        ElMessage.error(response.message || '密码重置失败')
      }
    } catch (error) {
      // 密码重置失败处理
      ElMessage.error('密码重置失败')
    }
  })
}

// 导入用户
const handleImport = () => {
  importDialogVisible.value = true
  uploadFile.value = null
}

// 文件选择改变
const handleFileChange = (file) => {
  uploadFile.value = file.raw
}

// 上传前验证
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB!')
    return false
  }
  return false // 阻止自动上传
}

// 上传文件
const handleUpload = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  uploadLoading.value = true
  try {
    const response = await importUsers(uploadFile.value)
    if (response.code === 200) {
      ElMessage.success('导入成功')
      importDialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    // 导入功能失败处理
    ElMessage.error('导入失败')
  } finally {
    uploadLoading.value = false
  }
}

// 导出数据
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 这里需要实现导出功能，可以调用后端接口或前端导出
    ElMessage.info('导出功能开发中...')
  } catch (error) {
    // 导出功能失败处理
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 下载模板
const downloadTemplate = () => {
  // 这里实现模板下载功能
  ElMessage.info('模板下载功能开发中...')
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: null,
    username: '',
    realName: '',
    gender: '',
    className: '',
    college: '',
    phone: '',
    email: '',
    roleId: null,
    passwordHash: '',
    confirmPassword: '',
    isActive: true
  })
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 使用Pinia store进行登出
    await authStore.logout()
    // 跳转到登录页
    router.push('/login')
  })
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 获取角色标签类型
const getRoleTagType = (roleName) => {
  const typeMap = {
    '管理员': 'danger',
    '老师': 'warning',
    '裁判': 'info',
    '学生': 'primary',
    '志愿者': 'success'
  }
  return typeMap[roleName] || 'primary'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 手机号脱敏
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 生命周期钩子
onMounted(() => {
  // 设置表格高度
  setTableHeight()
  window.addEventListener('resize', setTableHeight)

  // 加载数据
  loadData()
})

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', setTableHeight)
})
</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

/* 全局变量 */
:root {
  --primary-color: #2C5AA0;
  --primary-light: #E8EFF9;
  --primary-dark: #1E3D73;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --text-primary: #303133;
  --text-regular: #606266;
  --text-secondary: #909399;
  --text-placeholder: #C0C4CC;
  --border-light: #EBEEF5;
  --border-base: #DCDFE6;
  --border-lighter: #F2F6FC;
  --background-base: #F5F7FA;
  --background-light: #FAFAFA;
}

/* 容器布局 */
.app-container {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: var(--background-base);
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
}

.logo {
  font-size: 20px;
  font-weight: 600;
  color: white;
  display: flex;
  align-items: center;
  gap: 12px;
  letter-spacing: 0.5px;
}

.flex-grow {
  flex-grow: 1;
}

/* 用户信息区域 */
.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid var(--border-light);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.menu-item {
  padding: 14px 24px;
  color: var(--text-regular);
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  font-weight: 500;
  position: relative;
}

.menu-item:hover {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: var(--primary-color);
}

.menu-item span {
  font-size: 15px;
}

/* 主内容区 */
.content {
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title h1 {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.page-desc {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 0;
}

.search-card :deep(.el-card__body) {
  padding: 24px;
}

.advanced-search {
  margin-top: 20px;
}

/* 表格卡片 */
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-light);
}

.table-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 表格样式 */
:deep(.el-table) {
  flex: 1;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: var(--background-light) !important;
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: var(--primary-light);
}

/* 表格操作按钮组 */
:deep(.el-button-group .el-button) {
  margin-left: 0;
}

:deep(.el-button-group .el-button + .el-button) {
  margin-left: 1px;
}

/* 分页容器 */
.pagination-container {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid var(--border-light);
}

/* 批量操作栏 */
.batch-operations {
  padding: 16px 24px;
  background-color: var(--primary-light);
  border-top: 1px solid var(--border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--primary-color);
}

.batch-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: var(--primary-color);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid var(--border-light);
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input .el-input__inner) {
  border-radius: 4px;
}

/* 导入内容 */
.import-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.import-template {
  text-align: center;
  margin: 12px 0;
}

/* 用户详情样式 */
.user-detail {
  padding: 8px 0;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  color: var(--text-regular);
}

/* 按钮激活状态 */
:deep(.el-button.is-active) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  border-radius: 8px;
  border: 2px dashed var(--border-base);
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: var(--primary-color);
}

/* 消息提示样式 */
:deep(.el-message) {
  border-radius: 4px;
}

:deep(.el-message-box) {
  border-radius: 8px;
}

/* 桌面端样式优化 */
.app-container {
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
}

/* 动画效果 */
.el-fade-in-enter-active,
.el-fade-in-leave-active {
  transition: opacity 0.3s ease;
}

.el-fade-in-enter-from,
.el-fade-in-leave-to {
  opacity: 0;
}

.el-zoom-in-enter-active,
.el-zoom-in-leave-active {
  transition: all 0.3s ease;
}

.el-zoom-in-enter-from,
.el-zoom-in-leave-to {
  transform: scale(0.9);
  opacity: 0;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--background-light);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--border-base);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--text-placeholder);
}
</style>